/*
 * 文件名：RealStreamDataServer.java
 * 版权：亚信联创版权所有
 * 描述：TODO
 * 修改人：yuanze
 * 修改时间：2014年11月13日
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.protocal.aipr.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ailk.bigdata.etl.realstream.server.protocal.aipr.netty.handler.RealStreamDataDecode;

/**
 * 
 * @description 接收实时数据流server监听
 * @author [xuwei3]
 * @version [版本号,2014-11-12]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class StreamDataAcceptServer
{
	private static Logger logger = LoggerFactory.getLogger(StreamDataAcceptServer.class);

	private int port;

	public StreamDataAcceptServer(int port)
	{
		this.port = port;
	}

	public void run(final ChannelInboundHandlerAdapter handler) throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 8);
		EventLoopGroup workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 8);
		try
		{
			ServerBootstrap server = new ServerBootstrap();
			server.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					// .option(ChannelOption.SO_KEEPALIVE, true)
					.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_RCVBUF, 1048576 * 4)
					.option(ChannelOption.SO_SNDBUF, 1048576 * 4).option(ChannelOption.AUTO_READ, true)
					.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).handler(new LoggingHandler(LogLevel.WARN))
					.childHandler(new ChannelInitializer<SocketChannel>()
					{
						@Override
						public void initChannel(SocketChannel ch) throws Exception
						{
							ch.pipeline().addLast("byteToMess", new RealStreamDataDecode()).addLast("encoder", new StringEncoder())
									.addLast("handler", handler);
						}
					});
			server.bind(port).sync().channel().closeFuture().sync();
		}
		catch (Exception e)
		{
			logger.error("开启监听失败！端口[" + port + "]", e);
		}
		finally
		{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args)
	{

	}
}
